package com.nciae.restcontroller;

import com.nciae.converter.OrderForm2OrderDTOConverter;
import com.nciae.dto.OrderDTO;
import com.nciae.enums.ResultEnum;
import com.nciae.exception.SellException;
import com.nciae.form.OrderForm;
import com.nciae.service.IOrderMasterService;
import com.nciae.utils.ResultVoUtils;
import com.nciae.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private IOrderMasterService orderMasterService;

    @PostMapping("/create")
    public ResultVo<Map<String, String>> create(@Valid  @RequestBody OrderForm orderForm,
                                                BindingResult bindingResult
                                                ) throws SellException {
        if (bindingResult.hasErrors()) {
            throw new SellException(
                    bindingResult.getFieldError().getDefaultMessage(),
                    ResultEnum.PARAM_ERROR.getCode());
        }
        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            throw new SellException(ResultEnum.CART_EMPTY);
        }
        OrderDTO createResult = orderMasterService.create(orderDTO);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("orderId", orderDTO.getOrderId());
        return ResultVoUtils.success(hashMap);
    }

}